import grace from "../../utils/grace.js"
grace.page({
      data: {
            imgUrls: [],
            store: {
                  cover_img: '../../image/auth_logo.png',
              store_name: '通发物业商城官方旗舰店',
                  address: '',
                  allow_change: 0, //是否允许切换门店 ,
                  delivery_desc: '',
                  notice: '',
                  store_type: 1
            },
            hasMore: false,
            searchParam: {
                  pageSize: 20,
                  pageCurrent: 1
            },
            recomment: [],
            screenWidth: 375,
            img_height: 150,
            imgwidth: 0,
            imgheight: 0,
            bar: {
                  text: '',
                  scrollable: true,
                  delay: 1000,
                  color: '#000',
                  speed: 100,
                  backgroundColor: '#FFF'
            },
            ad: {
                  list: [],
                  distribution: '通发物业商城',
                  refund: '无条件赔付',
                  security: ''
            },
            other: {},
            project: {}
      },
      wxLocation: function(e) {
            var _this = this;
            if (e) {
                  _this.$data.project = e.project;
            } else {
                  wx.getLocation({
                        type: 'gcj02',
                        success: function(res) {
                              console.log("用户当前位置 success:" + JSON.stringify(res));
                              //     _this.$http.get('/api/home/get_index_project', { latitude: res.latitude, longitude: res.longitude }).then((res) => {
                              //       _this.$data.project = res;
                              //     });
                        },
                        fail(error) {
                              console.log("用户当前位置 fail:" + JSON.stringify(error));
                              _this.getSetting()
                                    .then((res) => {
                                          if (!res.authSetting["scope.userLocation"]) {
                                                // return Servs.authorizeServs.getAuthorize("scope.userLocation");
                                                return _this.openSetting();
                                          }
                                    })
                                    .then((res) => {
                                          // that.init();
                                          if (!res.authSetting["scope.userLocation"]) {
                                                wx.showToast({
                                                      title: '授权失败，请刷新页面授权..',
                                                      icon: "none",
                                                      duration: 1500
                                                });
                                          } else {
                                                that.init();
                                          }
                                    })
                                    .catch((error) => {
                                          wx.showToast({
                                                title: '授权失败，请刷新页面授权..',
                                                icon: "none",
                                                duration: 1500
                                          });
                                    })
                        }
                  })
            }
      },
      openDetail: function(e) {
            let goods_id = e.currentTarget.dataset.goods;
            wx.navigateTo({
                  url: '../product_details/product_details?goods_id=' + goods_id,
            })
      },
      toCharge: function() {
            wx.navigateTo({
                  url: '/pages/money_charge/money_charge',
            })
      },
      toExchange: function() {
            wx.navigateTo({
                  url: '/pages/exchange_card/exchange_card',
            })
      },
      openBook: function(e) {
            let tab = e.currentTarget.dataset.tab;
            wx.navigateTo({
                  url: '../menu_strategy/menu_strategy?tab=' + tab,
            })
      },
      onLoad: function(options) {
            var _this = this;
            wx.getSystemInfo({
                  success: function(res) {
                        _this.setData({
                              screenHeight: res.windowHeight,
                              screenWidth: res.windowWidth,
                              img_height: res.windowWidth / 2.5
                        });
                  }
            });

            let token = wx.getStorageSync('api_token');
            if (!token) {
                  grace.bus.$emit("usre_logout_success");
            } else {
                  this.wxLocation();
                  //this.loadStore();
                  this.loadData();
                  this.loadRecommend();
            }
      },
      onShow: function() {
            let token = wx.getStorageInfoSync('api_token');
            if (token && token.length != 0) {
                  this.loadCoupon();
            }
      },
      loadCoupon: function() {
            this.$http.get('/api/home/coupon_info', {}).then((res) => {
                  this.$data.other = res;
            });
      },
      loadData: function() {
            this.$http.get('api/article/ad_list?ad_position=app_home').then((res) => {
                  this.$data.ad = res;
            });
      },
      loadRecommend: function() {
            let that = this;
            this.$http.get('api/goods/recommend_list').then((res_recommend) => {
                  var isHasMore = res_recommend.list.length >= that.$data.searchParam.pageSize;
                  const data = that.$data.searchParam.pageCurrent == 1 ? res_recommend.list : that.$data.recomment.concat(res_recommend.list);
                  that.$data = {
                        recomment: data,
                        isHasMore: isHasMore,
                        isHideLoadMore: true
                  };
            });
      },
      loadData2: function() {
            var ad = this.$http.get('api/article/ad_list');
            var recommend = this.$http.get("api/goods/recommend_list", this.data.searchParam);
            let store_id = this.$data.store_id;
            let store = this.$http.get("/api/home/store_info", {
                  store_id: store_id
            });
            let that = this;
            this.$http.all([ad, recommend, store])
                  .then(this.$http.spread(function(res_ad, res_recommend, res_store) {
                        if (res_ad) {
                              that.$data.ad = res_ad;
                        }
                        if (res_recommend) {
                              var isHasMore = res_recommend.list.length >= that.$data.searchParam.pageSize;
                              const data = that.$data.searchParam.pageCurrent == 1 ? res_recommend.list : that.$data.recomment.concat(res_recommend.list);
                              that.$data = {
                                    recomment: data,
                                    isHasMore: isHasMore,
                                    isHideLoadMore: true
                              };
                        }
                        if (res_store) {
                              that.$data.store = res_store;
                              that.$data.bar.text = res_store.notice;
                        }
                  }));
      },
      userLoginSuccessCallback: function() {
            if (parseInt(this.$data.store_id) <= 0) {
                  this.$data.store_id = wx.getStorageSync('current_store');
            }
      },
      loadStore: function() {
            let store_id = this.$data.store_id;
            this.$http.get("/api/home/store_info", {
                  store_id: store_id
            }).then((res) => {
                  this.$data.store = res;
                  this.$data.bar.text = res.notice;
            }).catch(err => {
                  if (err.status == 400) {
                        wx.navigateTo({
                              url: '../stores/stores'
                        })
                  }
            });
      },
      //跨页面传值  
      $onBackData(data) {
            if (data && data.store_id) {
                  this.$data.store_id = data.store_id;
                  this.loadStore();
            }
      },
      addToCart: function(e) {
            let goods_id = e.currentTarget.dataset.goods;
            this.$http.post('api/cart/add_goods', {
                  goods_vals: goods_id
            }).then((res) => {
                  this.toast(res.message);
            });
      },
      handleAd: function(e) {
            let index = e.currentTarget.dataset.index;
            let adlink = this.$data.ad.list[index]['link'];
            let adtype = e.currentTarget.dataset.type;
            if (parseInt(adtype) == 3) {
                  wx.navigateTo({
                        url: adlink,
                  });
            } else if (parseInt(adtype) == 2) {
                  let url = encodeURIComponent(adlink);
                  wx.navigateTo({
                        url: '../adweb/adweb?url=' + adlink
                  });
            }
      },
      toCoupon: function(e) {
            let url = encodeURIComponent(e.currentTarget.dataset.url);
            wx.navigateTo({
                  url: '../adweb/adweb?url=' + url
            });
      },
      changeStore: function(e) {
            if (parseInt(this.$data.store.allow_change) == 1) {
                  wx.navigateTo({
                        url: '../stores/stores'
                  })
            }
      },
      showProjectList: function(e) {
            let project_info = e.currentTarget.dataset.project_info;
            wx.navigateTo({
                  url: '../project/project_list?project_name=' + project_info.title + '&latitude=' + project_info.location.lat + '&longitude=' + project_info.location.lng,
            })
      },
      onPullDownRefresh: function() {
            this.$data.searchParam.pageCurrent = 1;
            this.loadData();
            this.loadRecommend();
            this.wxLocation();
      },
      onShareAppMessage: function() {
            let user_id = wx.getStorageSync('user_id');
            let from_store = wx.getStorageSync('current_store');
            let share_url = 'pages/index/index?user=' + user_id + '&from_store=' + from_store;
            let share_title = this.$data.ad.share || '通发物业商城';
            return {
                  title: share_title,
                  path: share_url,
                  success: function(res) {

                  },
                  fail: function(res) {
                        // 转发失败
                  }
            }
      },
      getSetting() {
            return new Promise((resovle, reject) => {
                  wx.getSetting({
                        success: (res) => {
                              console.log("获取设置权限 success" + JSON.stringify(res));
                              resovle(res);
                        },
                        fail(error) {
                              console.log("获取设置权限 fail" + JSON.stringify(res));
                              reject(error);
                        }
                  })
            });
      },
      openSetting() {
            return new Promise((resovle, reject) => {
                  wx.openSetting({
                        success: (res) => {
                              console.log("用户设置权限 success" + JSON.stringify(res));
                              resovle(res);
                        },
                        fail(error) {
                              console.log("用户设置权限 fail" + JSON.stringify(res));
                              reject(error);
                        }
                  })
            });
      },
})